package com.example.chessbattleplatform.Interceptor;

import com.example.chessbattleplatform.Pojo.Exception.BusinessException;
import com.example.chessbattleplatform.Pojo.Exception.StatusCode;
import com.example.chessbattleplatform.utils.JwtUtils;
import com.example.chessbattleplatform.utils.UserIdThreadLocalStorage;
import com.example.chessbattleplatform.utils.UserLoginHistoryIsCachedUtils;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


@Component
@Slf4j
@RequiredArgsConstructor
// 解析用户信息
public class GetUserTokenInterceptorInformation {

    //jwt token
    private final JwtUtils jwtUtils;
    // 缓存
    private final UserLoginHistoryIsCachedUtils userLoginHistoryIsCachedUtils;


    // 负责解析用户token
    // 如果token为空，则返回登录页面
    // 如果token不为空，则验证token是否正确，如果正确，则返回true，否则返回 BusinessException
    // 并存储到 线程本地存储中 和 判断缓存数据是否存在
    public boolean userToken(String token) {
        return getUserTokenId(token) != null;
    }

    public String getUserTokenId(String token) {

        // 如果token为空，则返回登录页面
        if (token == null || token.isEmpty()) {
            throw new BusinessException(StatusCode.UNAUTHORIZED, "Token为空");
        }

        Claims bearer;
        try {
            // 解析token
            bearer = jwtUtils.parseJWT(token);
        } catch (Exception e) {
            // 如果解析失败，则返回登录页面
            throw new BusinessException(StatusCode.UNAUTHORIZED, "Token验证失败");
        }

        //bearer = Map.of("uid", login.getId(), "pwd", login.getPassword());
        String uid = bearer.get("uid").toString();

//        log.info("Token用户id为：{}", uid);

        //设置线程用户token数据
        UserIdThreadLocalStorage.setUserToken(token);

        // 判断缓存数据是否存在
        String userLoginHistoryJwt = userLoginHistoryIsCachedUtils.getUserLoginHistory(uid);


        if (userLoginHistoryJwt == null || userLoginHistoryJwt.isEmpty() || !userLoginHistoryJwt.equals(token)) {
            throw new BusinessException(StatusCode.UNAUTHORIZED, "用户不存在");
        }

        return uid;
    }


}
